package com.yehebl.orm.config;

import com.yehebl.orm.dto.ClassInfo;
import com.yehebl.orm.dto.FieldInfo;
import com.yehebl.orm.enums.IdType;
import com.yehebl.orm.manager.ReadClassManager;
import com.yehebl.orm.util.LogUtil;

/**
 * 实体属性设置
 * 实体对应表设置
 *
 * @author tzd
 */
public class EntityPropertiesSet {


    /**
     * 设置实体对应表名关系
     */
    public void setTableName(Class<?> clazz, String tableName) {
        LogUtil.printInfo("设置[" + clazz.getName() + "]对应的表名为[" + tableName + "]");
        ClassInfo classInfo = ReadClassManager.map.get(clazz.getName());
        if (classInfo == null) {
            throw new RuntimeException(clazz.getName() + "不存在,无法重新设置表名");
        }
        classInfo.setTableName(tableName);
    }


    /**
     * 设置实体字段对应表字段关系
     */
    public void setColumnName(Class<?> clazz, String fieldName, String columnName) {
        LogUtil.printInfo("设置表字段对应列名关系[" + clazz.getName() + "." + fieldName + "]对应的列名为[" + columnName + "]");
        ClassInfo classInfo = ReadClassManager.map.get(clazz.getName());
        if (classInfo == null) {
            throw new RuntimeException(clazz.getName() + "不存在,无法重新设置表名");
        }
        for (FieldInfo fi : classInfo.getAllFieldMap().values()) {
            if (fi.getFieldName().equals(fieldName)) {
                fi.setTableFieldName(columnName);
                classInfo.getTableFieldMap().put(fi.getTableFieldName(), fi);
                classInfo.getFieldMap().put(fi.getFieldName(), fi);
                return;
            }
        }
    }

    /**
     * 设置id生成类型
     */
    public void setColumnIdType(Class<?> clazz, String fieldName, IdType idType) {
        LogUtil.printInfo("设置实体属性字段自动生成id[" + clazz.getName() + "." + fieldName + "]生成类型为[" + idType.toString() + "]");
        ClassInfo classInfo = ReadClassManager.map.get(clazz.getName());
        if (classInfo == null) {
            throw new RuntimeException(clazz.getName() + "不存在,无法重新设置表名");
        }
        for (FieldInfo fi : classInfo.getAllFieldMap().values()) {
            if (fi.getFieldName().equals(fieldName)) {
                fi.setIdType(idType);
                return;
            }
        }
    }

    /**
     * 设置id 字段
     */
    public void setId(Class<?> clazz, String... idFieldName) {
        ClassInfo classInfo = ReadClassManager.map.get(clazz.getName());
        if (classInfo == null) {
            throw new RuntimeException(clazz.getName() + "不存在,无法重新设置表名");
        }
        classInfo.getIdFieldInfo().clear();
        for (FieldInfo fi : classInfo.getAllFieldMap().values()) {
            for (String s : idFieldName) {
                if (fi.getFieldName().equals(s)) {
                    classInfo.getIdFieldInfo().add(fi);
                    LogUtil.printInfo("重新设置表字段[" + clazz.getName() + "." + s + "]为id");
                }
            }
        }
    }


}
